import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/dialog/dialog_utils.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/order_detail_mode.dart';
import 'package:loxen/utils/app_enum_util.dart';
import 'package:loxen/utils/color.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/time_util.dart';
import 'package:loxen/widget/my_subassembly.dart';

class OrderDetailListCard extends StatelessWidget {
  final OrderDetailMode orderDetailMode;
  final bool staff;
  final Function() onSuccess;

  const OrderDetailListCard({Key key, this.orderDetailMode, this.staff = false, this.onSuccess})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 5,
      child: Container(
        padding: EdgeInsets.fromLTRB(20.w, 30.h, 20.w, 30.h),
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CachedNetworkImage(
              imageUrl: ImageUrlUtil.getClean(orderDetailMode.brand.logo),
              height: 24.h,
              fit: BoxFit.fitHeight,
            ),
            Padding(
              padding: EdgeInsets.only(top: 40.h),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: Text(
                      '订单编号：${orderDetailMode.orderNumber}',
                      style: TextStyle(
                        fontSize: 28.sp,
                        color: Colours.dark_text_gray,
                      ),
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Clipboard.setData(ClipboardData(
                        text: orderDetailMode.orderNumber,
                      ));
                      Toast.show('已复制到剪贴板', context);
                    },
                    child: Text(
                      '复制编号',
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: Colours.app_main,
                      ),
                    ),
                  )
                ],
              ),
            ),
            ListView.builder(
                itemCount: orderDetailMode.products.length,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (context, index) {
                  var product = orderDetailMode.products[index];
                  return Container(
                    margin: EdgeInsets.only(top: 30.h),
                    height: 150.h,
                    child: Row(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(10.w),
                          child: CachedNetworkImage(
                            imageUrl: ImageUrlUtil.getClean(product.cover, w: 150),
                            placeholder: (_, __) => Constants.loadingIcon(),
                            fit: BoxFit.cover,
                            width: 150.h,
                            height: 150.h,
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.only(left: 20.w),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  product.hsName,
                                  style: TextStyle(
                                    fontSize: 32.sp,
                                    fontWeight: FontWeight.bold,
                                    color: Colours.main_text,
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(top: 30.h),
                                  child: Row(
                                    children: [
                                      Text(
                                        '编号：${product.hsCode}',
                                        style: TextStyle(
                                          fontSize: 28.sp,
                                          color: Colours.main_text,
                                        ),
                                      ),
                                      Padding(
                                        padding: EdgeInsets.only(left: 20.w),
                                        child: Text(
                                          "规格：${product.size}",
                                          style: TextStyle(
                                            fontSize: 28.sp,
                                            color: Colours.main_text,
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  );
                }),
            Padding(
              padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
              child: Divider(
                height: 1.h,
              ),
            ),
            createState(),
            createButton(context),
          ],
        ),
      ),
    );
  }

  Widget stateContent(String time, _MyPainter _myPainter, String content) {
    var timeData = time.split('_');
    return Container(
      height: 110.h,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 95.w,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  timeData[0],
                  style: TextStyle(
                    fontSize: 24.sp,
                    color: Colours.main_text,
                  ),
                ),
                Text(
                  timeData[1],
                  style: TextStyle(
                    fontSize: 24.sp,
                    color: Colours.main_text,
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: 65.w,
            height: double.infinity,
            child: CustomPaint(
              painter: _myPainter,
            ),
          ),
          Expanded(
            child: Text(
              content,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 28.sp,
                color: Colours.main_text,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget createState() {
    List<Widget> list = [];
    var status = orderDetailMode.status.reversed.toList();
    for (int i = 0; i < status.length; i++) {
      _Type _type;
      if (i == 0) {
        _type = _Type.FIRST;
      } else if (status[i].state == '9') {
        _type = _Type.END;
      } else {
        _type = _Type.CENTER;
      }
      list.add(stateContent(
        TimeUtil.getStateTime(status[i].time),
        _MyPainter(_type, i < status.length - 1),
        StateMap[status[i].state],
      ));
    }
    list = list.reversed.toList();
    return Column(
      children: list,
    );
  }

  Widget createButton(BuildContext context) {
    if (staff) {
      return Row(
        children: [
          Expanded(child: Constants.empty),
          Padding(
            padding: EdgeInsets.only(right: 20.w),
            child: MySubassembly.getButtonLine(() async {
              String text = await showDialog(
                  context: context,
                  builder: (_) => DialogUtil.editContentDialog(context, '备注', '请输入备注内容'));
              if (text != null && text.trim() != '') {
                ApiService.orderRemark(orderDetailMode.id.toString(), text).listen((event) {
                  Toast.show('备注完成', context);
                }, onError: (error, stack) {
                  print(error);
                  print(stack);
                  Toast.show('备注失败', context);
                });
              }
            }, text: '备注', height: 66.h),
          ),
          createStaffButton(context),
        ],
      );
    } else {
      Widget confirmButton;
      if (orderDetailMode.state == '3' ||
          orderDetailMode.state == '4' ||
          orderDetailMode.state == '6') {
        confirmButton = MySubassembly.getButton(() {
          ApiService.orderOk(orderDetailMode.id.toString()).listen((event) {
            Toast.show('确认收样完成', context);
            if (onSuccess != null) onSuccess.call();
          }, onError: (error, stack) {
            print(error);
            print(stack);
            Toast.show('确认订单失败', context);
          });
        }, text: '确认收样', height: 66.h);
      } else {
        confirmButton = MySubassembly.getButton(null, text: '确认收样', height: 66.h);
      }
      Widget changeTime = Constants.empty;
      // if (orderDetailMode.mode != '3' && (checkState())) {
      //   changeTime = Padding(
      //     padding: EdgeInsets.only(right: 20.w),
      //     child: MySubassembly.getButtonLine(() {}, text: '修改送样时间', height: 66.h),
      //   );
      // }
      return Row(
        children: [
          Expanded(child: Constants.empty),
          // Padding(
          //   padding: EdgeInsets.only(right: 20.w),
          //   child: MySubassembly.getButtonLine(() {}, text: '取消订单', height: 66.h),
          // ),
          changeTime,
          confirmButton,
        ],
      );
    }
  }

  Widget createStaffButton(BuildContext context) {
    var state = orderDetailMode.state;
    if (state == '1' || state == '9') {
      return Constants.empty;
    } else {
      return MySubassembly.getButton(() {
        ApiService.orderNext(orderDetailMode.id.toString()).listen((event) {
          if (onSuccess != null) onSuccess.call();
        }, onError: (error, stack) {
          print(error);
          print(stack);
          Toast.show('操作失败', context);
        });
      }, text: StaffMap[orderDetailMode.state], height: 66.h);
    }
  }

  bool checkState() {
    return orderDetailMode.state != '9' &&
        orderDetailMode.state != '8' &&
        orderDetailMode.state != '7' &&
        orderDetailMode.state != '6' &&
        orderDetailMode.state != '5';
  }
}

enum _Type {
  FIRST,
  CENTER,
  END,
}

class _MyPainter extends CustomPainter {
  _Type type;
  bool after;
  double radius;

  Paint circular = Paint()
    ..color = Colours.app_main
    ..style = PaintingStyle.fill;

  Paint alphaCircular = Paint()
    ..color = Colours.app_main.withAlpha(76)
    ..style = PaintingStyle.fill;

  Paint line = Paint()
    ..color = Colours.app_main
    ..style = PaintingStyle.stroke
    ..strokeWidth = 3.w
    ..isAntiAlias = true;

  Paint lineG = Paint()
    ..color = Color(0xffCFCFCF)
    ..style = PaintingStyle.stroke
    ..strokeWidth = 3.w
    ..isAntiAlias = true;

  _MyPainter(this.type, this.after);

  @override
  void paint(Canvas canvas, Size size) {
    radius = 8.h;
    // Paint _paint = Paint()
    //   ..strokeCap = StrokeCap.round //画笔笔触类型
    //   ..isAntiAlias = true //是否启动抗锯齿
    //   ..blendMode = BlendMode.exclusion //颜色混合模式
    //   ..style = PaintingStyle.stroke //绘画风格，默认为填充
    //   ..colorFilter = ColorFilter.mode(
    //       Colors.blueAccent, BlendMode.exclusion) //颜色渲染模式，一般是矩阵效果来改变的,但是flutter中只能使用颜色混合模式
    //   ..maskFilter = MaskFilter.blur(BlurStyle.inner, 3.0) //模糊遮罩效果，flutter中只有这个
    //   ..filterQuality = FilterQuality.high //颜色渲染模式的质量
    //   ..strokeWidth = 3.w //画笔的宽度
    //   ..color = Colours.app_main;
    // canvas.drawLine(Offset(size.width / 2, 0), Offset(size.width / 2, size.height), _paint);
    switch (type) {
      case _Type.FIRST:
        drawFirst(canvas, size.width, size.height, after);
        break;
      case _Type.CENTER:
        drawCenter(canvas, size.width, size.height, after);
        break;
      case _Type.END:
        drawEnd(canvas, size.width, size.height, after);
        break;
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }

  void drawFirst(Canvas canvas, double x, double y, bool after) {
    var w = x / 2;
    canvas.drawLine(Offset(w, 0), Offset(w, 18.h), after ? line : lineG);
    if (after) {
      canvas.drawCircle(Offset(w, 18.h), radius, circular);
    } else {
      canvas.drawCircle(Offset(w, radius + 10.h), radius + 4.h, alphaCircular);
      canvas.drawCircle(Offset(w, radius + 10.h), radius, circular);
    }
  }

  void drawCenter(Canvas canvas, double x, double y, bool after) {
    var w = x / 2;
    if (after) {
      canvas.drawLine(Offset(w, 0), Offset(w, y), line);
    } else {
      canvas.drawLine(Offset(w, radius + 10.h), Offset(w, y), line);
      canvas.drawLine(Offset(w, 0), Offset(w, radius + 10.h), lineG);
    }
    if (after) {
      canvas.drawCircle(Offset(w, radius + 10.h), radius, circular);
    } else {
      canvas.drawCircle(Offset(w, radius + 10.h), radius + 4.h, alphaCircular);
      canvas.drawCircle(Offset(w, radius + 10.h), radius, circular);
    }
  }

  void drawEnd(Canvas canvas, double x, double y, bool after) {
    var w = x / 2;
    canvas.drawLine(Offset(w, radius + 10.h), Offset(w, y), line);
    if (after) {
      canvas.drawCircle(Offset(w, radius + 10.h), radius, circular);
    } else {
      canvas.drawCircle(Offset(w, radius + 10.h), radius + 4.h, alphaCircular);
      canvas.drawCircle(Offset(w, radius + 10.h), radius, circular);
    }
  }
}
